<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <!-- 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮 -->
    <form class="search-form" action="/">
      <van-search background="#3296fa" v-model="searchText" show-action placeholder="请输入搜索关键词" @search="onSearch"
        @cancel="onCancel" @focus="isResultShow = false" />
    </form>
    <!-- 搜索栏 -->
    <!-- 搜索结果 -->
    <search-result :searchText="searchText" v-if="isResultShow"></search-result>
    <!-- 联想建议 -->
    <search-suggestion @search="onSearch" :searchText="searchText" v-else-if="searchText"></search-suggestion>
    <!-- 搜索记录 -->
    <search-history v-else @delete="onDelete" @search="onSearch" @clearDataSearch="searchHistories = []"
      :searchHistories="searchHistories"></search-history>

  </div>
</template>

<script>
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import searchHistory from './components/searchHistory.vue'
import searchResult from './components/searchResult.vue'
import searchSuggestion from './components/searchSuggestion.vue'
import { setItem, getItem } from '@/utils/storage'
export default {
  name: 'Search',
  components: {
    searchHistory,
    searchResult,
    searchSuggestion
  },
  setup () {
    const searchText = ref('')
    const isResultShow = ref(false)// 控制搜索结果的展示
    const searchHistories = ref(getItem('TOUTIAO_SEARCH_HISTORY') || [])
    const router = useRouter()
    // watch 来统一管理历史记录
    watch(searchHistories.value, (newValue, oldValue) => {
      setItem('TOUTIAO_SEARCH_HISTORY', newValue)
    })
    const onDelete = (index) => {
      searchHistories.value.splice(index, 1)
    }
    // 回车调用
    const onSearch = (val) => {
      // 更新文本框内容
      searchText.value = val

      // 存储搜索历史记录
      // 要求不要有重复历史记录 同时按时间排序
      const index = searchHistories.value.indexOf(val)
      if (index !== -1) {
        searchHistories.value.splice(index, 1)
      }
      searchHistories.value.unshift(val)

      //   渲染搜索结果
      isResultShow.value = true
    }
    // 点击取消返回首页
    const onCancel = () => {
      router.back()
      // 搜索结果清空
      isResultShow.value = false
    }
    return {
      searchText,
      onSearch,
      onCancel,
      isResultShow,
      searchHistories,
      onDelete
    }
  }
}
</script>

<style scoped lang="less">
.search-container {
  padding-top: 108px;

  :deep(.van-search__action) {
    color: #fff;
  }

  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 3;
  }
}
</style>
